package com.ipay.wechat.util;



import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ipay.wechat.component.Wechat;
import com.ipay.wechat.pojo.AccessToken;
import com.ipay.wechat.pojo.WXTicket;

public class AccessTokenUtil {
	private static Logger logger = LoggerFactory.getLogger(AccessTokenUtil.class);

	public static AccessToken freshAccessToken(Wechat wechat) {
		AccessToken accessToken =new AccessToken(); 
		String result = HttpUtils.requestHttp(
				"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
						+ wechat.getAppId() + "&secret=" + wechat.getSecret(),
				"get", "");
		logger.info("result=="+result);
		if (result.contains("access_token")) {
			JSONObject jsonObject = JSONObject.fromObject(result);
			accessToken.setAccess_token(jsonObject.getString("access_token"));
			accessToken.setExpire_in(jsonObject.getInt("expires_in"));
			return accessToken;
		} else {
			return null;
		}
	}

	/**
	 * 获得jsapi_ticket
	 * @param token
	 * @return
	 */
	public static WXTicket freshTicket(String token) {
		WXTicket ticket = new WXTicket();
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
				+ token + "&type=jsapi";
		String result = HttpUtils.requestHttp(url, "get", "");
		if (result.contains("ticket")) {
			JSONObject ticketObject = JSONObject.fromObject(result);
			ticket.setExpires_in(ticketObject.getInt("expires_in"));
			ticket.setTicket(ticketObject.getString("ticket"));
			return ticket;
		} else {
			return null;
		}
	}


}
